<template>
  <view class="form-page-container">
    <wd-form 
      ref="formRef" 
	  :rules="rules"
      :model="formData" 
      class="form-wrapper"
    >
      <wd-cell-group border>
        <FieldFormItem
          v-for="(field, idx) in formFields"
          :key="idx"
          :type="field.type"
          :label="field.label"
          :label-width="field.labelWidth || '100px'"
          :prop="field.prop"
          :input-type="field.inputType"
          :clearable="field.clearable"
          v-model="formData[field.prop]"
          :placeholder="field.placeholder"
          :columns="field.columns"
          :upload-action="field.uploadAction"
          @upload:change="(fileList) => handleFileChange(fileList, field.prop)"
          @change="handleSelectChange"
          @confirm="handlePickerConfirm"
        />
      </wd-cell-group>

      <view class="submit-btn-container">
        <wd-button type="primary" @click="handleSubmit" block>保存信息</wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import FieldFormItem from '@/components/FieldFormItem/index.vue'

// 表单实例
const formRef = ref(null)

// 表单数据 
const formData = reactive({
  username: '',
  phone: '',
  platform: [],
  promotion: '',
  fileList: [] // 初始为空数组
})

// 选择器选项
const platformList = [
  { label: '微信', value: 'wechat' },
  { label: '抖音', value: 'douyin' },
  { label: '小红书', value: 'xiaohongshu' },
  { label: '微博', value: 'weibo' }
]
const promotionList = [
  { label: '满减优惠', value: 'discount' },
  { label: '赠品活动', value: 'gift' },
  { label: '限时折扣', value: 'limited' }
]

// 手机号验证器 - 修复了原有的逻辑错误
const phoneValidator = (target) => {
  const value = target.value
  const phoneReg = /^1[3-9]\d{9}$/
  
  if (!value) {
    return Promise.resolve() // 非必填，空值时验证通过
  } else if (value.length !== 11) {
    return Promise.reject('请输入11位手机号')
  } else if (!phoneReg.test(value)) {
    return Promise.reject('手机号格式不正确')
  }
  
  return Promise.resolve()
}

const rules={
	username:[{
		required: true, message: '请输入用户名'
	}],
	phone:[
		  { required: true,message:"请输入手机号",validator: phoneValidator }
	],
	platform: [
      { required: true, message: '请选择推广平台' }
    ],
	promotion:[
		  { required: true, message: '请选择优惠方式' }
	],
	fileList: [
	    {
	      required: true,
	      message: '请选择活动图片',
	      validator: (value) => {
	        if (Array.isArray(value) && value.length) {
	          return Promise.resolve()
	        } else {
			formData.fileList=[];
	          return Promise.reject()
	        }
	      }
	    }
	]
}

// 表单项配置
const formFields = [
	{
	  type: 'upload-cell',
	  label: '头像',
	  prop: 'fileList',
	  labelWidth: '100px',
	  uploadAction: 'https://ftf.jd.com/api/uploadImg'
	},
	{
	  type: 'input',
	  label: '手机号',
	  prop: 'phone',
	  inputType: 'tel',
	  clearable: true,
	  placeholder: '请输入手机号'
	},
	{
	  type: 'input',
	  label: '联系电话',
	  prop: 'contact',
	  inputType: 'text',
	  clearable: true,
	  placeholder: '联系电话'
	},
  {
    type: 'input',
    label: '联系地址',
    prop: 'username',
    inputType: 'text',
    clearable: true,
    placeholder: '请输入联系地址'
  }
]

// 上传事件处理
const handleFileChange = (fileList, prop) => {
  // 确保是数组
  const validList = Array.isArray(fileList) ? fileList : []
  // 过滤无效文件
  const filteredList = validList.filter(file => {
    // 大小限制5MB
    const sizeValid = file.size <= 5 * 1024 * 1024
    // 格式限制：图片
    const typeValid = file.type.startsWith('image/')
    
    if (!sizeValid) {
      uni.showToast({ title: '图片不能超过5MB', icon: 'none' })
    }
    if (!typeValid) {
      uni.showToast({ title: '请上传图片格式文件', icon: 'none' })
    }
    
    return sizeValid && typeValid
  })
  
  formData[prop] = filteredList
}

// 监听fileList变化
watch(() => formData.fileList, (newVal) => {
  if (!Array.isArray(newVal)) {
    console.error('⚠️ fileList被修改为非数组！当前值：', newVal)
    formData.fileList = [] // 强制恢复为数组
  }
}, { deep: true })

// 选择器事件处理
const handleSelectChange = (selectedValue) => {
  formData.platform = selectedValue
}

const handlePickerConfirm = (value) => {
  formData.promotion = value
}

// 表单提交处理
const handleSubmit = async () => {
  try {
    if (!formRef.value) {
      uni.showToast({ title: '表单实例未找到！', icon: 'none' })
      return
    }
    
    // 触发验证
    const { valid, errors } = await formRef.value.validate()
    
    if (valid) {
      uni.showLoading({ title: '提交中...' })
      
      // 提交前最后校验fileList
      const submitData = {
        ...formData,
        fileList: Array.isArray(formData.fileList) ? formData.fileList : []
      }
      
      // 模拟接口请求
      setTimeout(() => {
        uni.hideLoading()
        uni.showToast({ title: '保存成功！', icon: 'success' })
        
        // 重置表单
        Object.keys(formData).forEach(key => {
          formData[key] = key === 'fileList' ? [] : ''
        })
      }, 1000)
    } else {
      // 显示第一个错误
      const firstErr = errors[0]?.message || '表单填写有误'
      // uni.showToast({ title: firstErr, icon: 'none' })
    }
  } catch (err) {
    uni.hideLoading()
    // 显示错误信息
    uni.showToast({ title: err.message || '提交失败，请重试', icon: 'none' })
  }
}
</script>

<style scoped>
.form-page-container {
  background-color: #f5f5f7;
  min-height: 100vh;
}
.submit-btn-container { padding: 16px; margin-top: 10px; }
::v-deep .wd-button { height: 50px; font-size: 16px; border-radius: 8px; }
::v-deep .wd-form-item__error { display: none !important; } /* 确保错误文字不显示 */
::v-deep .wd-cell .wd-upload { width: 100%; padding: 5px 0; }
::v-deep .wd-upload__preview { margin-top: 8px; gap: 8px; }
</style>
